package by.cooker.chat.logic.listeners;

import java.awt.event.ActionEvent;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;

import by.cooker.chat.gui.Window;
import by.cooker.chat.logic.Client;
import by.cooker.chat.logic.Configuration;
import by.cooker.chat.logic.Printer;
import by.cooker.chat.logic.Receiver;
import by.cooker.chat.logic.User;

/**
 * @author cooker
 */
public class ConnectAction extends AbstractAction
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private boolean connected = false;
	private User user;
	private Window window;

	/**
	 * ConnectListener constructor.
	 * 
	 * @param window
	 *            owner window.
	 */
	public ConnectAction(Window window)
	{
		this.window = window;
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (!connected)
		{
			user = Configuration.getConf().getUser();
			if (!validateUser(user))
			{
				JOptionPane
						.showMessageDialog(
								null,
								"<html>This is not correct.<br>"
										+ "Please check the correctness of the data<br>"
										+ "in the file properties.</htmL>");
			} else
			{
				connect(user);
				connected = true;
			}
		}
	}

	/**
	 * Connect to the server.
	 * 
	 * @param user
	 *            user data.
	 */
	private void connect(User user)
	{
		try
		{
			Client.getClient().connect(user);
			LinkedBlockingQueue<String> messages = new LinkedBlockingQueue<String>();
			new Thread(new Receiver(messages)).start();
			new Thread(new Printer(window, messages)).start();
			connected = true;
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}

	/**
	 * Method validate user data.
	 * 
	 * @param user
	 *            user data.
	 * @return <b>false</b> if user data is not correct and <b>true</b> if user
	 *         data correct.
	 */
	private boolean validateUser(User user)
	{
		String login = user.getLogin();
		char[] password = user.getPassword();
		String host = user.getHost();
		int port = user.getPort();
		String channel = user.getChannel();

		if (login == null || login.length() == 0 || password == null
				|| password.length == 0 || host == null || host.length() == 0
				|| port < 0 || channel == null || channel.length() == 0)
		{
			return false;
		}
		return true;
	}
}
